package 排序;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Author Weton Li
 * @Date 2021/3/21 15:17
 */
public class 合并区间 {

    public int[][] merge(int[][] intervals) {
        List<int[]> result = new ArrayList<int[]>();
        // 先对原数组按左边界排序
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        // 遍历排序后的数组，逐个判断合并
        for (int[] interval : intervals) {
            int left = interval[0], right = interval[1];
            int length = result.size();
            if (length == 0 || left > result.get(length - 1)[1]) {
                result.add(interval);
            } else {
                int mergedLeft = result.get(length - 1)[0];
                int mergedRight = Math.max(result.get(length - 1)[1], right);
                result.set(length - 1, new int[]{mergedLeft, mergedRight});
            }
        }
        return result.toArray(new int[result.size()][]);
    }


}
